window.addEventListener('DOMContentLoaded', function () {
    // 根据数据渲染页面
    function render() {
        this.document.querySelector('.container').innerHTML = `
        <div class="media">
        <div class="goods-image">
          <div class="middle">
            <div class="mask"></div>
            <img src="${mainPictures[0]}" alt="" />
            <div class="max"></div>
          </div>
          <div>
            <ul class="small">
              <li><img src="${mainPictures[0]}" alt="" /></li>
              <li><img src="${mainPictures[1]}" alt="" /></li>
              <li><img src="${mainPictures[2]}" alt="" /></li>
              <li><img src="${mainPictures[3]}" alt="" /></li>
              <li><img src="${mainPictures[4]}" alt="" /></li>
            </ul>
          </div>
        </div>
        <ul class="goods-sales">
          <li>
            <p>销量人气</p>
            <p>100+</p>
            <p><i class="toutiao">&#xe8ad;</i> 销量人气</p>
          </li>
          <li>
            <p>商品评价</p>
            <p>200+</p>
            <p><i class="toutiao">&#xe612;</i> 查看评价</p>
          </li>
          <li>
            <p>收藏人气</p>
            <p>80+</p>
            <p><i class="toutiao">&#xe63a;</i> 收藏商品</p>
          </li>
          <li>
            <p>品牌信息</p>
            <p>90+</p>
            <p><i class="toutiao">&#xe613;</i> 品牌主页</p>
          </li>
        </ul>
      </div>
      <div class="spec">
        <div class="goods-main">
          <p class="g-name">${name}</p>
          <p class="g-desc">${desc}</p>
          <p class="g-price">
            <span>${price}</span>
            <span>${oldPrice}</span>
          </p>
          <div class="g-service">
            <dl>
              <dt>促销</dt>
              <dd>12月好物放送，App领券购买直降120元</dd>
            </dl>
            <dl>
              <dt>配送</dt>
              <dd>至</dd>
              <dd>
                <div class="xtx-city">
                  <div class="select">
                    <span class="placeholder"
                      >请选择配送地址 <i class="toutiao">&#xe650;</i></span
                    >
                  </div>
                  <div class="option"></div>
                </div>
              </dd>
            </dl>
            <dl>
              <dt>服务</dt>
              <dd>
                <span>无忧退货</span><span>快速退款</span><span>免费包邮</span
                ><a href="javascript:;">了解详情</a>
              </dd>
            </dl>
          </div>
        </div>
        <div class="goods-sku">
          <dl>
            <dt>${specs[0].name}</dt>
            <dd>
              <img class="" src="${specs[0].values[0].picture}" data-sp="单功能"/>
              <img class="" src="${specs[0].values[1].picture}" data-sp="多功能"/>
            </dd>
          </dl>
          <dl>
            <dt>${specs[1].name}</dt>
            <dd>
              <span class="">${specs[1].values[0].name}</span>
              <span class="">${specs[1].values[1].name}</span>
              <span class="">${specs[1].values[2].name}</span>
            </dd>
          </dl>
        </div>
        <div class="xtx-numbox" style="margin: 20px 0px">
          <div class="label">数量</div>
          <div class="numbox">
            <a href="javascript:;">-</a>
            <input type="text" readonly="" value="1" />
            <a href="javascript:;">+</a>
          </div>
        </div>
        <button class="xtx-button ellipsis middle primary">加入购物车</button>
      </div>
        `
    }
    const { result: { children: [{ goods: [{ detail: { name, desc, price, oldPrice, mainPictures, specs, skus } }] }] } } = mygoodsdata
    render()
    const small = this.document.querySelector('.small')
    // 绑定自定义属性
    for (let i = 0; i < small.children.length; i++) {
        small.children[i].dataset.index = i + 1;
    }
    small.children[0].classList.add('active')
    // 鼠标经过添加类
    small.addEventListener('mouseover', function (e) {
        if (e.target.tagName === 'IMG') {
            const li = document.querySelector('li.active')
            li.classList.remove('active')
            e.target.parentNode.classList.add('active')
            const num = e.target.parentNode.dataset.index
            const temp = document.querySelector('.middle>img')
            const max = document.querySelector('.middle .max')
            temp.src = `${mainPictures[num - 1]} `
            max.style.backgroundImage = `url(${mainPictures[num - 1]})`;
        }
    })
    // 鼠标移入移出，显示隐藏
    const middle = this.document.querySelector('.media .middle')
    const mask = document.querySelector('.mask')
    const max = document.querySelector('.max')
    middle.addEventListener('mouseenter', function () {
        mask.style.display = 'block'
        max.style.display = 'block'
    })
    middle.addEventListener('mouseleave', function () {
        mask.style.display = 'none'
        max.style.display = 'none'
    })
    // mask跟随鼠标移动
    middle.addEventListener("mousemove", function (e) {
        let X = e.pageX - middle.offsetLeft - mask.offsetWidth / 2
        let Y = e.pageY - middle.offsetTop - mask.offsetHeight / 2;
        // 限制鼠标的移动范围
        if (X < 0) { X = 0 }
        if (Y < 0) { Y = 0 }
        if (X > middle.offsetWidth - mask.offsetWidth) {
            X = middle.offsetWidth - mask.offsetWidth
        }
        if (Y > middle.offsetHeight - mask.offsetHeight) {
            Y = middle.offsetHeight - mask.offsetHeight
        }
        mask.style.left = X + 'px'
        mask.style.top = Y + 'px'
        // max背景图片移动
        max.style.backgroundPosition = `-${2 * X}px -${2 * Y}px`;
    })
    // 点击切换
    const goodsSku = this.document.querySelector('.goods-sku')
    const dd = this.document.querySelector('.goods-sku dl dd')
    const dd2 = this.document.querySelector('.goods-sku dl:nth-child(2) dd')
    for (let i = 0; i < dd.children.length; i++) {
        dd.children[i].dataset.s = i
    }
    for (let i = 0; i < dd2.children.length; i++) {
        dd2.children[i].dataset.ss = i
    }
    let num1 = ''
    let num2 = ''
    goodsSku.addEventListener('click', function (e) {
        if (e.target.tagName === 'IMG') {
            if (e.target.classList.contains('actives')) {
                e.target.classList.remove('actives')
            } else {
                for (let i = 0; i < dd.children.length; i++) {
                    dd.children[i].classList.remove('actives')
                }
                e.target.classList.add('actives')
                num1 = e.target.dataset.s
            }
        }
        if (e.target.tagName === 'SPAN') {
            if (e.target.classList.contains('actives')) {
                e.target.classList.remove('actives')
            } else {
                for (let i = 0; i < dd2.children.length; i++) {
                    dd2.children[i].classList.remove('actives')
                }
                e.target.classList.add('actives')
                num2 = e.target.dataset.ss
            }
        }
        const price = document.querySelector('.spec .g-price span:nth-child(1)')
        const oldPrice = document.querySelector('.spec .g-price span:nth-child(2)')
        const { result: { children: [{ goods: [{ detail: { skus } }] }] } } = mygoodsdata
        const skuss = skus.slice(dd2.children.length, 2 * (dd2.children.length))
        for (let i = 0; i < dd2.children.length; i++) {
            if (num1 === `0`) {
                if (num2 === `${i}`) {
                    price.innerHTML = skus[num2].price
                    oldPrice.innerHTML = skus[num2].oldPrice
                }
            }
            if (num1 === `1`) {
                if (num2 === `${i}`) {
                    price.innerHTML = skuss[num2].price
                    oldPrice.innerHTML = skuss[num2].oldPrice
                }
            }
        }
    })
    // 数量加减
    let num = 1
    const numbox = this.document.querySelector('.numbox')
    const minus = numbox.children[0]
    const input = numbox.children[1]
    const add = numbox.children[2]
    add.addEventListener('click', function () {
        num++
        input.value = num
    })
    minus.addEventListener('click', function () {
        num--
        if (num < 1) {
            num = 1
        }
        input.value = num
    })
    // 城市选择
    const strs = `{
        "name": "陕西省",
        "city": [
            {
                "name": "西安市",
                "area": [
                    "莲湖区",
                    "新城区",
                    "碑林区",
                    "雁塔区",
                    "灞桥区",
                    "未央区",
                    "阎良区",
                    "临潼区",
                    "长安区",
                    "高陵县",
                    "蓝田县",
                    "户县",
                    "周至县",
                    "其他"
                ]
            },
            {
                "name": "铜川市",
                "area": [
                    "耀州区",
                    "王益区",
                    "印台区",
                    "宜君县",
                    "其他"
                ]
            },
            {
                "name": "宝鸡市",
                "area": [
                    "渭滨区",
                    "金台区",
                    "陈仓区",
                    "岐山县",
                    "凤翔县",
                    "陇县",
                    "太白县",
                    "麟游县",
                    "扶风县",
                    "千阳县",
                    "眉县",
                    "凤县",
                    "其他"
                ]
            },
            {
                "name": "咸阳市",
                "area": [
                    "秦都区",
                    "渭城区",
                    "杨陵区",
                    "兴平市",
                    "礼泉县",
                    "泾阳县",
                    "永寿县",
                    "三原县",
                    "彬县",
                    "旬邑县",
                    "长武县",
                    "乾县",
                    "武功县",
                    "淳化县",
                    "其他"
                ]
            },
            {
                "name": "渭南市",
                "area": [
                    "临渭区",
                    "韩城市",
                    "华阴市",
                    "蒲城县",
                    "潼关县",
                    "白水县",
                    "澄城县",
                    "华县",
                    "合阳县",
                    "富平县",
                    "大荔县",
                    "其他"
                ]
            },
            {
                "name": "延安市",
                "area": [
                    "宝塔区",
                    "安塞县",
                    "洛川县",
                    "子长县",
                    "黄陵县",
                    "延川县",
                    "富县",
                    "延长县",
                    "甘泉县",
                    "宜川县",
                    "志丹县",
                    "黄龙县",
                    "吴起县",
                    "其他"
                ]
            },
            {
                "name": "汉中市",
                "area": [
                    "汉台区",
                    "留坝县",
                    "镇巴县",
                    "城固县",
                    "南郑县",
                    "洋县",
                    "宁强县",
                    "佛坪县",
                    "勉县",
                    "西乡县",
                    "略阳县",
                    "其他"
                ]
            },
            {
                "name": "榆林市",
                "area": [
                    "榆阳区",
                    "清涧县",
                    "绥德县",
                    "神木县",
                    "佳县",
                    "府谷县",
                    "子洲县",
                    "靖边县",
                    "横山县",
                    "米脂县",
                    "吴堡县",
                    "定边县",
                    "其他"
                ]
            },
            {
                "name": "安康市",
                "area": [
                    "汉滨区",
                    "紫阳县",
                    "岚皋县",
                    "旬阳县",
                    "镇坪县",
                    "平利县",
                    "石泉县",
                    "宁陕县",
                    "白河县",
                    "汉阴县",
                    "其他"
                ]
            },
            {
                "name": "商洛市",
                "area": [
                    "商州区",
                    "镇安县",
                    "山阳县",
                    "洛南县",
                    "商南县",
                    "丹凤县",
                    "柞水县",
                    "其他"
                ]
            }]
    }`
    const str = JSON.parse(strs);
    const city = str.city.map(function (e) {
        return `<span class="ellipsis">${e.name}</span>`
    })
    const area = str.city[0].area.map(function (e) {
        return `<span class="ellipsis">${e}</span>`
    })
    const select = this.document.querySelector('.select')
    const option = this.document.querySelector('.xtx-city .option')
    const span = select.children[0]
    select.addEventListener('click', function () {
        option.style.display = 'flex'
        option.innerHTML = `
                    <span class="ellipsis">北京</span>
                    <span class="ellipsis">天津</span>
                    <span class="ellipsis">河北省</span>
                    <span class="ellipsis">山西省</span>
                    <span class="ellipsis">内蒙古自治区</span>
                    <span class="ellipsis">辽宁省</span>
                    <span class="ellipsis">吉林省</span>
                    <span class="ellipsis">黑龙江省</span>
                    <span class="ellipsis">上海</span>
                    <span class="ellipsis">江苏省</span>
                    <span class="ellipsis">浙江省</span>
                    <span class="ellipsis">安徽省</span>
                    <span class="ellipsis">福建省</span>
                    <span class="ellipsis">江西省</span>
                    <span class="ellipsis">山东省</span>
                    <span class="ellipsis">河南省</span>
                    <span class="ellipsis">湖北省</span>
                    <span class="ellipsis">湖南省</span>
                    <span class="ellipsis">广东省</span>
                    <span class="ellipsis">广西壮族自治区</span>
                    <span class="ellipsis">海南省</span>
                    <span class="ellipsis">重庆</span>
                    <span class="ellipsis">四川省</span>
                    <span class="ellipsis">贵州省</span>
                    <span class="ellipsis">云南省</span>
                    <span class="ellipsis">西藏自治区</span>
                    <span class="ellipsis">陕西省</span>
                    <span class="ellipsis">甘肃省</span>
                    <span class="ellipsis">青海省</span>
                    <span class="ellipsis">宁夏回族自治区</span>
                    <span class="ellipsis">新疆维吾尔自治区</span>
                    <span class="ellipsis">台湾省</span>
                    <span class="ellipsis">香港特别行政区</span>
                    <span class="ellipsis">澳门特别行政区</span>
        `
        for (let i = 0; i < option.children.length; i++) {
            option.children[i].dataset.index = i
        }
        let temp = ''
        let temp1 = ''
        option.addEventListener('click', function (e) {
            if (e.target.dataset.index === '26') {
                option.innerHTML = city.join('')
                for (let i = 0; i < option.children.length; i++) {
                    option.children[i].dataset.indexs = i
                }
                temp = e.target.innerHTML
                span.innerHTML = temp
            }
            if (e.target.dataset.indexs === '0') {
                option.innerHTML = area.join('')
                for (let i = 0; i < option.children.length; i++) {
                    option.children[i].dataset.indexe = i
                }
                temp1 = e.target.innerHTML
                span.innerHTML = `${temp}-${temp1}`
            }
            if (e.target.dataset.indexe === '5') {
                span.innerHTML = `${temp}-${temp1}-${e.target.innerHTML}`
            }
        })
    })
    option.addEventListener('mouseleave', function () {
        option.style.display = 'none'
    })
    // 加入购物车进行本地存储
    const btn = this.document.querySelector('.xtx-button.ellipsis.middle.primary')
    const arr = []
    const newArr = []

    let flag = true
    btn.addEventListener('click', function () {
        if (flag) {
            flag = false
            // 点击判断
            const imgAct = dd.querySelectorAll('img')
            const imgSpa = dd2.querySelectorAll('span')
            let temp1 = false
            let temp2 = false
            let temp3 = false
            for (let i = 0; i < imgAct.length; i++) {
                if (imgAct[i].classList.contains('actives')) {
                    temp1 = true
                }
            }
            for (let i = 0; i < imgSpa.length; i++) {
                if (imgSpa[i].classList.contains('actives')) {
                    temp2 = true
                }
            }
            const spt = document.querySelector('.xtx-city .select span').innerHTML
            if (spt !== `请选择配送地址 <i class="toutiao"></i>`) {
                temp3 = true
            }
            if (temp1 && temp2 && temp3) {
                const shopCarList = {
                    name: document.querySelector('.spec .g-name').innerHTML,
                    desc: document.querySelector('.spec .g-desc').innerHTML,
                    price: document.querySelector('.spec .g-price span:nth-child(1)').innerHTML,
                    oldPrice: document.querySelector('.spec .g-price span:nth-child(2)').innerHTML,
                    picture: document.querySelector('.goods-image .middle img').src,
                    number: parseInt(document.querySelector('.xtx-numbox .numbox > input').value),
                    massage: document.querySelector('.xtx-city .select span').innerHTML,
                    style: dd2.querySelectorAll('span')[num2].innerHTML,
                    specification: dd.querySelectorAll('img')[num1].dataset.sp,
                    isSel: true
                }
                arr.push(shopCarList)
                // 进行数组去重和重复对象的价格，相同后进行数量相加
                const result = arr.reduce((acc, curr) => {
                    const index = acc.findIndex((item) => item.price === curr.price && item.oldPrice === curr.oldPrice);
                    if (index !== -1) {
                        acc[index].number += curr.number;
                    } else {
                        acc.push(curr);
                    }
                    return acc;
                }, []);

                localStorage.setItem('shopCarList', JSON.stringify(result))

                new Dialog({
                    //默认参数
                    bgColor: "#f0f9eb",
                    text: "添加购物车成功",
                    color: "#69c241",
                    borderColor: "rgb(225, 243, 216)",
                })
            } else {
                new Dialog({
                    //默认参数
                    bgColor: "#fdf6ec",
                    text: "请选择商品规格和收货地址~",
                    color: "#e3a343",
                    borderColor: "rgb(225, 243, 216)",
                    cls: 'icon toutiao icon-jingti'
                })
            }
            setTimeout(function () {
                flag = true
            }, 2000)
        }
        renderShop()
    })

})